import { CSSProperties, useEffect, useRef, useState } from "react";
import { initVirtual } from "./virtual";

export interface VirtualScrollListProps {
  dataSources: any[];
  size: number;
  DataComponent: React.FC<any>;
  dataKey: string;
  estimateSize: number;
}
export interface RangeOptions {
  start: number;
  end: number;
  padFront: number;
  padBehind: number;
}
const VirtualScrollList = (props: VirtualScrollListProps) => {
  const { dataSources, size, DataComponent, dataKey, estimateSize } = props;
  const [range, setRange] = useState<RangeOptions>({} as RangeOptions);
  const [paddingStyle, setPaddingStyle] = useState<CSSProperties>({});
  const getUniqueIdFromDataSource = () => {
    return dataSources.map((item) => dataSources[dataKey as any]) as string[];
  };
  const vir = useRef() as any;
  useEffect(() => {
    vir.current = initVirtual(
      {
        size: size,
        buffer: Math.round(size / 3),
        uniqueIds: getUniqueIdFromDataSource(),
        estimateSize,
      },
      setRange
    );
  }, []);

  useEffect(() => {
    const { padFront, padBehind } = range;
    setPaddingStyle(() => {
      return {
        padding: `${padFront}px 0 ${padBehind}px 0`,
      };
    });
  }, [range]);

  const renderComponent = () => {
    const component = [];
    const { start, end } = range;
    for (let index = start; index <= end; index++) {
      const dataSource = dataSources[index];
      const uniqueKey = dataSource[dataKey];
      if (dataSource) {
        component.push(
          <DataComponent
            key={uniqueKey}
            source={dataSource}
            estimateSize={estimateSize}
          />
        );
      }
    }

    return component;
  };
  const root = useRef<HTMLDivElement>(null);
  const handleOnScroll = (e: React.UIEvent<HTMLDivElement>) => {
    if (root.current) {
      const offset = root.current.scrollTop;
      vir.current.handleScroll(offset);
    }
  };
  return (
    <div
      onScroll={handleOnScroll}
      className="coerger-"
      ref={root}
      style={{
        width: "100%",
        height: "300px",
        overflow: "scroll",
        border: "1px solid red",
      }}
    >
      <div style={paddingStyle}>{renderComponent()}</div>
    </div>
  );
};

export default VirtualScrollList;
